<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" ref="tableRef">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleInit()" :disabled="btnIsDisabled">初始化</a-button>
        <a-button type="primary" v-if="!startEdit" @click="handleEdit" :disabled="btnIsDisabled">批量编辑</a-button>
        <a-button type="primary" v-if="startEdit" @click="handleSave">保存</a-button>
        <a-button v-if="startEdit" @click="handleCancel">取消</a-button>
      </template>
      <template #bodyCell="{ column, text, record, index }">
        <a-input-number v-if="column.editComponent === 'Custom_InputNumber' && startEdit" @change="scoreCompute" @focus="handleIndex(index)" v-model:value="record[column['dataIndex']]" addon-after="个" :min="0" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="emp-team-checkIn3-HubTeamResultQuota" setup>
// @ts-nocheck
import { ref, nextTick, onMounted, reactive } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { Modal } from 'ant-design-vue';
import { columns, searchFormSchema } from './HubTeamResultQuotaData';
import { list, deleteOne, updateList, getColumn, init, getExportUrl, getImportUrl } from './HubTeamResultQuota.api';
import dayjs from 'dayjs';
import { getMonitoringStatus } from '/@/api/common/api';
import { cloneDeep } from 'lodash-es';
const queryParam = reactive<any>({});
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

// 轻提醒
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage: $message } = useMessage();

//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '基础积分定额',
    api: list,
    columns,
    canResize: false,
    showIndexColumn: true,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    beforeFetch: (params) => {
      startEdit.value = false;
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "基础积分定额",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
});

const [registerTable, { getForm, reload, getDataSource, getColumns, setColumns, setTableData }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;


const btnIsDisabled = ref(false);

const startEdit = ref(false);

let currentTableIndex = 0;
// 默认执行一次
const orgName = ref(userStore.getOrgName);
onMounted(async () => {
  let form = getForm();
  getTableColumn(userStore.getOrgCode);
  //获取编辑按钮的状态
  getBtnStatus();
  form.updateSchema([
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e,i) => {
          setTableData([]);
          orgName.value = i?.label;
          getTableColumn(e);
          getBtnStatus();
          reload();
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
});

/**
 * 动态表头配置
 * @param orgCode
 */
const getTableColumn = (orgCode) => {
  getColumn({ orgCode: orgCode }).then((res) => {
    let newColumn = cloneDeep(columns);
    res.forEach((r) => {
      let temp = {
        title: r.headName,
        dataIndex: r.headCode,
        width: 140,
        align: 'center',
        editComponent: 'Custom_InputNumber',
      };
      newColumn.splice(newColumn.length - 1, 0, {
        ...temp,
      });
    });
    //重设表头
    setColumns(newColumn);
  });
};

const handleIndex = (index) => {
  currentTableIndex = index;
};

// 计算基础定额积分
const scoreCompute = () => {
  let tableData = getDataSource();
  let column = getColumns();
  let currentRecord = tableData[currentTableIndex];
  currentRecord.finalScore = 0;
  column.forEach((c) => {
    if (c.editComponent === 'Custom_InputNumber' && currentRecord[c.dataIndex]) {
      currentRecord.finalScore += currentRecord[c.dataIndex];
    }
  });
  // if (currentRecord.)
};

// 初始化
const handleInit = () => {
  let formData = getForm().getFieldsValue();
  const saveMsg = '初始化';
  const msg = '确认要' + saveMsg + '吗？';
  Modal.confirm({
    title: '确认',
    content: msg,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      init({
        orgCode: formData.orgCode,
        periodCode: formData.periodCode,
      }).then((res) => {
        // console.log('res', res);
        reload();
      });
    },
  });
};

const handleEdit = () => {
  startEdit.value = true;
};

async function handleSave() {
  let records = getDataSource();
  let orgCode = getForm().getFieldsValue().orgCode;
  let periodCode = getForm().getFieldsValue().periodCode;
  //封装提交的数据
  records.forEach((item) => {
    item.periodCode = periodCode;
    item.orgCode = orgCode;
    item.orgName = orgName.value;
  });
  await updateList({
    datas: records,
    orgCode: orgCode,
  });
  await reload();
  startEdit.value = false;
  checkedKeys.value = [];
  startAdd.value = false;
};

const handleCancel = () => {
  // let columns = getColumns();
  // let newColumns = columns.map((item) => {
  //   if (item.dataIndex == 'score') {
  //     return {
  //       title: '基础定额积分',
  //       dataIndex: 'finalScore',
  //       width: 140,
  //       align: 'center',
  //     };
  //   } else {
  //     return item;
  //   }
  // });
  // setColumns(newColumns);
  startEdit.value = false;
};

const getBtnStatus = () => {
  getMonitoringStatus({
    orgCode: getForm().getFieldsValue().orgCode,
    periodCode: getForm().getFieldsValue().periodCode,
  }).then((res) => {
    btnIsDisabled.value = res.data == '2';
  });
};

/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}

/**
 * 表格操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      icon: 'clarity:note-edit-line',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '删除',
      icon: 'ant-design:delete-outlined',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}
</script>
<style lang="less" scoped>
.btn {
  margin-right: 8px;
}
</style>
